import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup,  Validators } from '@angular/forms';
import { SFSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalService ,NzModalRef} from 'ng-zorro-antd';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import * as moment from 'moment';
import { reader } from '../../../../../assets/js/rdapi.js'
import { UtilService } from '@core/services/util.service';
declare var QRCode

@Component({
  selector: 'app-cardRessiue',
  templateUrl: './card-ressiue.component.html',
  styles:[`.qrcode{text-align:center}`]
})
export class CardRessiueComponent implements OnInit {
  @Input()userName:any;
  @Input()id:any;
  @Input()doorCard:any;
  @Input()xnCardNo:any
  @Input()xuDate:any;//续期时的初始化日期
  @Input()startDate:any;
  @Input() roomId:string;
  @Input()
  set program(value:any){
    if(!value) return;
    this.monthlyRent=value.monthlyRent / 100;
    this.itemId=value.itemId;
  }
  loginUser:string;
  userId:string;
  cardNo:string;
  itemId:any;
  validateForm!: FormGroup;
  param: any;
  cashMoney:number = 0.01;//押金
  monthlyRent:number=0;//月租
  totalMoney:number = 0.01;//总计
  manageMoney:number = 0;//管理费
  month:number = 0;//有效期
  index:number = 0;
  cardList:any=[];
  permissionList:any=[];
  g_device:string="00";
  g_isOpen:boolean= false;
  g_wantFunc:number=0;
  angularxQrCode: string = '';

  desNum="";
  readData=0;//读出的数据
  pwd="FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";//密钥
  num=0;//web认证的次数 现在设置为两次，两次不成功的话就不再继续
  inNum=0;//代表创建两个二进制文件
  select=0;//复位
  random=0;//获取随机数
  delfile=0;//擦除MF下的数据
  createSK=0;//创建密钥文件
  sk=0;//增加外部认证密钥
  createTwo=0;//创建二进制文件
  writeFile=0;//写入二进制文件
  readFile=0;//读取二进制文件
 
  constructor(private http: HttpClient,private util:UtilService,  private api: ApiService,private modal: NzModalService, private modalRef: NzModalRef, private message: NzMessageService,private fb: FormBuilder) { }
  ngOnInit() {
    let userData:any=this.util.getStorage("userNow");
    userData=JSON.parse(userData);
    this.loginUser=userData.userName;
    this.userId=userData.id;
    if(reader.SocketOpen){
      this.connect();
    }else{
      reader.createSocket();
      setTimeout(()=>{
        this.connect();
      },200)
    }
    this.getPermission();
    this.validateForm = this.fb.group({
      userName: [{value:this.userName,disabled:true}, [Validators.required]],
      date: [{value:null,disabled:true}, [Validators.required]],
     // doorCard:[null],
      cardNo:[null, [Validators.required]],
      remark:[null],
      cardCode:[null,[Validators.required]],
      xnCardNo:[null,[Validators.required]]
    });
    this.validateForm.patchValue({
      date:this.xuDate
    })

    reader.onResult((rData:any)=>{
      console.log(rData)
      this.inNum++;
      if(rData.strCmdCode == "1203"){
        let str=rData.strData;
        let a=str.substring(str.length-4,str.length);
        if(a != "9000" ){//证明出现错误
          if(this.delfile == 1){//代表密钥错误，需要用新的密钥，然后获取并发送八字节加密数据
            this.select=1;
            this.delfile=0;
            this.pwd="0123321456654789987ABCDEFFEDCBC1";//用新的密钥去认证
            if(this.num == 2){//如果认证两次依然错误的话，则不再继续
              this.message.error('密钥错误')
              return;
            }
          }else{
            return;
          }
        }
      }

      if(this.readData == 1){//代表读取二进制文件
        this.cardList.unshift({
          "cardNo":this.cardNo
        });
        this.checkCard();
       let n=rData.strData.slice(0,16);
       this.validateForm.patchValue({
        xnCardNo:n
      })
       this.readData=0;
      }
      
      if(this.select == 1 ){//获取随机数 已复位
        this.getRandom();
        this.random=1;
        this.select=0;
      }else if(this.random == 1 ){//发送八字节加密数据
        //获取八字节加密数据，然后发送八字节加密数据
        this.getDesNum(rData.strData.slice(0,16)).then((res)=>{
          this.getNumber();
        });
        this.num++;
        this.delfile=1;
        this.random=0;
      }else if(this.delfile == 1 ){
        this.delData();
        this.createSK=1;
        this.delfile=0;
      }else if(this.createSK == 1 ){
        this.createFile();
        this.sk=1;
        this.createSK=0;
      }else if(this.sk == 1 ){
        this.addSK();
        this.createTwo=1;
        this.sk=0;
      }else if(this.createTwo == 1 ){
        this.createHex();
        this.writeFile=1;
        this.createTwo=0;
        this.inNum=0;
      }else if(this.writeFile == 1 && this.inNum == 2){//index=2代表两个二进制文件已经创建完成，然后执行写二进制文件
        this.writeHex();
        this.writeFile=0;
        this.readFile=1;
        this.inNum=0;
      }else if(this.readFile == 1 && this.inNum == 2){//读取二进制文件  index=2代表两个二进制文件已经写入完成，可以执行读二进制文件
        this.readHex();
        this.readFile=0;
        this.readData=1;
      }

      switch(rData.strCmdCode){
        case "0007":
          if(rData.strStatus != "00"){
            this.message.error("连接设备失败!");
          }else{
            this.g_isOpen=true;
            console.log("连接成功")
          }
          break;
        case "1001":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
             case 1:
              reader.send(this.g_device + "1002"); //TyA_Anticollision
              break;
          }
          break;
        case "1002":
          if(rData.strStatus != "00"){
            return;
          }
          switch(this.g_wantFunc){
              case 1 :
                this.validateForm.patchValue({
                  cardNo:rData.strData
                })
                this.cardList.unshift({
                  "cardNo":rData.strData
                });
                this.cardNo=rData.strData;
                this.validateForm.patchValue({
                  xnCardNo:rData.strData
                })
                this.checkCard();
              break;
          }
          break;
          case "1202"://复位
            this.cardNo=rData.strData.slice(0,8);
            console.log("选择MF");
            reader.send(this.g_device + "1203" + "00A40000023F00");//选择MF
            this.select=1;
          break;
      }
     
    })
  }

  ngOnDestroy(){
    reader.Disconnect();
  }

  submitForm(value: any): void {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
      if(this.validateForm.controls[key].invalid){
        return;
      }
    }
  const body:any={
          "personId":this.id,
          "itemId": this.itemId,
          "payCodingId": this.doorCard,
          "oldCardId":this.xnCardNo,
          "payMoney": this.totalMoney * 100,
          "payWay": "3",
          "newCard": value.cardNo,
          "cardCode":value.cardCode,
          "newCardId":value.xnCardNo,
          "createId":this.userId,
          "createBy":this.loginUser,
          "monthServe":this.month,
          "monthMoney":this.monthlyRent * 100,//月租,
          "payDeposit":this.cashMoney * 100,//押金,
          "payRoom":this.roomId,
          "businessType":"3",
  }
    console.log(body);
    this.http.post(this.api.doorCard.reapplyCard.url,body).subscribe((res:any)=>{
      console.log(res);
      if (res.status == '200') {
          let url=res.data.data;
          const modal = this.modal.create({
            nzTitle: '付款码',
            nzContent: '<div class="qrcode"></div>',
            nzWidth: 400,
            nzFooter: [
              {
                label:"支付完成",
                type:"primary",
                onClick:()=>{
                   modal.close();
                   this.modalRef.triggerOk();
                }
              }
            ],
          })
          modal.afterOpen.subscribe(()=>{
            new QRCode(document.getElementsByClassName("qrcode")[0],{
              width:350,
              height:350
            }).makeCode(url);
          })
      } else {
        this.message.error(res.message)
      }
    })
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  //根据人员ID查询门禁权限
getPermission(){
  this.http.post(this.api.doorCard.searchPer.url,{"id":this.id}).subscribe((res:any)=>{
    this.permissionList=res.data;
  })
}

//读卡或者输完卡号之后，检查此卡是否已经被绑定
checkCard(){
  if(this.cardNo == "" || this.cardNo == undefined){
    return;
  }
  const that=this;
  this.http.get(this.api.doorCard.checkCard.url+this.cardNo).subscribe((res:any)=>{
    console.log(res);
    if(res.status == 200){
      if(res.data != null && res.data.personId != "" && res.data.personId != null){
            this.message.error("此卡已经被绑定!");
            setTimeout(function(){
              that.cardList.shift();
              that.cardNo="";
              that.validateForm.patchValue({
                xnCardNo:""
              })
            },1000);
        }
    }
  })
}

connect(){
	reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
	reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
  this.LedGreen();
  setTimeout(()=>{this.LedRed()},200);
  reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
}
/**
 * Turn on the green light
 * (亮绿灯)
**/
LedGreen()
{
  reader.send(this.g_device + "0107" + "02"); 
}

/**
 * Turn on the red light
 * (亮红灯)
**/
LedRed()
{
  reader.send(this.g_device + "0107" + "01"); 
}

read(){
  // if(this.g_isOpen != true){
  //   this.message.error("请连接读卡器!");
  //   return;
  // }
  this.num=0;
  this.selectMF();
}

//复位之后才能发送cos命令
selectMF(){
  console.log("复位");
  console.log(1);
  this.select=0;
  reader.send(this.g_device + "1202" + "26");//复位
}

//获取四字节随机数
getRandom(){
  console.log("获取八字节随机数")
  console.log(2);
  reader.send(this.g_device + "1203" + "0084000008");//获取四字节随机数
}

//发送八字节加密数据
getNumber(){
  console.log("发送八字节加密数据");
  console.log(3);
  console.log(this.desNum)
  reader.send(this.g_device + "1203" + "0082000008" + this.desNum);
}
//擦除MF下的数据
delData(){
  console.log("擦除MF下的数据");
  console.log(4);
  //擦除MF下的数据
  reader.send(this.g_device + "1203" + "800E000000");
}
//建立密钥文件
createFile(){
  //建立密钥文件
  console.log("建立密钥文件");
  console.log(5);
  reader.send(this.g_device + "1203" + "80E00000073F005001F1FFFF");
}
//增加外部认证密钥
addSK(){
  console.log("增加外部认证密钥");
  console.log(6);
  reader.send(this.g_device + "1203" + "80D401001539F0F1AADD"+"0123321456654789987ABCDEFFEDCBC1");
  //reader.send(g_device + "1203" + "80D401000D39F0F1AADD"+"FFFFFFFFFFFFFFFF");
}
//创建二进制文件
createHex(){
  console.log("创建二进制文件");
  console.log(7);
  reader.send(this.g_device + "1203" +"80E0001F07280020F0F1FFFF");//31号文件
  reader.send(this.g_device + "1203" +"80E0001A07280020F0F1FFFF");//26号文件
  
}
//写二进制文件
writeHex(){
  console.log("写二进制文件");
  console.log(8);
  this.getDesNum(this.cardNo+"00000000").then((res)=>{
    console.log('虚拟卡号',this.desNum)
    reader.send(this.g_device + "1203" +"00D69F0008"+"8F4C3814C3B499A9");//31号文件
    reader.send(this.g_device + "1203" +"00D69A0008"+this.desNum);//26号文件
  })
 
}
//读二进制文件
readHex(){
  console.log("读二进制文件");
  console.log(9);
  reader.send(this.g_device + "1203" +"00B09A0010");
}

//获取八字节加密数据
getDesNum(randomNum){
 return  new Promise((resolve)=>{
    this.http.post("/core/door/card/desCard?data="+randomNum+"&password="+this.pwd,{}).subscribe((res:any)=>{
      console.log(res)
      this.desNum=res.data
      resolve(res.data)
    })
  })
}


// //读卡
readCpu(){
  if(this.g_isOpen != true){
    this.message.error("请连接读卡器!");
    return;
  }
  //Start read UID
  reader.send(this.g_device + "1001" + "52"); //TyA_Request
  this.g_wantFunc = 1;  
  reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
}

// //连接读卡器
// Connect(){
// 	reader.send(this.g_device + "0007" + "00"); //Open the USB device with index number 0. (打开索引号为0的USB设备)
// 	reader.send(this.g_device + "0109" + "41"); //Set to ISO14443a working mode. (设置为ISO14443A工作模式)
// 	reader.send(this.g_device + "0108" + "01"); //Turn on the reader antenna. (打开读卡器天线)
//  this.LedGreen();
//  let that=this;
//   setTimeout(function(){that.LedRed()},200); 
//   reader.send(this.g_device + "0106" + "10"); //Beeps. (蜂鸣提示)
// }

// LedGreen(){
//  reader.send(this.g_device + "0107" + "02"); 
// }

// LedRed(){
//   reader.send(this.g_device + "0107" + "01"); 
// }
}
